<template>
  <view class="profile-container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading">
      <view class="loading-icon">
        <view class="spinner"></view>
      </view>
      <text>加载中...</text>
    </view>

    <!-- 加载失败 -->
    <view v-else-if="loadError" class="load-error">
      <text>加载失败: {{ errorMsg }}</text>
      <button @click="reload">重试</button>
      <view class="debug-info" v-if="debugInfo">
        <text>调试信息:</text>
        <text>{{ debugInfo }}</text>
      </view>
    </view>

    <!-- 已加载完成的内容 -->
    <view v-else>
      <!-- 用户信息区域（新增用户类型和地址） -->
      <view class="user-info">
        <view class="avatar">
          <image :src="userInfo.avatar || '/static/images/avatar.png'" mode="widthFix"></image>
        </view>
        <view class="user-detail">
          <text class="username">{{ userInfo.userName || '用户' }}</text>
          <text class="user-id">ID: {{ userInfo.userId || '未知' }}</text>
          <text class="user-type">类型: {{ userInfo.userType || '未设置' }}</text>
          <text class="user-address">地址: {{ userInfo.userAddress || '未设置' }}</text>
        </view>
      </view>
      
      <!-- 功能菜单区域 -->
      <view class="profile-menu">
        <view class="menu-group">
          <view class="menu-item" @click="goToRecharge">
            <view class="menu-icon">
              <image src="/static/images/wallet.png" mode="widthFix"></image>
            </view>
            <text class="menu-text">我的钱包</text>
            <text class="menu-amount">¥{{ userInfo.readyAmount || '0.00' }}</text>
            <image src="/static/images/arrow-right.png" mode="widthFix" class="menu-arrow"></image>
          </view>
          
          <view class="menu-item" @click="goToBills">
            <view class="menu-icon">
              <image src="/static/images/my-bills.png" mode="widthFix"></image>
            </view>
            <text class="menu-text">账单记录</text>
            <image src="/static/images/arrow-right.png" mode="widthFix" class="menu-arrow"></image>
          </view>
		  <view class="menu-item" @click="goToPhones">
		    <view class="menu-icon">
		      <image src="/static/images/my-bills.png" mode="widthFix"></image>
		    </view>
		    <text class="menu-text">我的电话号码</text>
		    <image src="/static/images/arrow-right.png" mode="widthFix" class="menu-arrow"></image>
		  </view>
        </view>
		
        
        <view class="menu-group">
          <view class="menu-item">
            <view class="menu-icon">
              <image src="/static/images/help.png" mode="widthFix"></image>
            </view>
            <text class="menu-text">帮助中心</text>
            <image src="/static/images/arrow-right.png" mode="widthFix" class="menu-arrow"></image>
          </view>
          
          <view class="menu-item">
            <view class="menu-icon">
              <image src="/static/images/settings.png" mode="widthFix"></image>
            </view>
            <text class="menu-text">设置</text>
            <image src="/static/images/arrow-right.png" mode="widthFix" class="menu-arrow"></image>
          </view>
        </view>
      </view>
      
      <!-- 退出登录按钮 -->
      <button class="logout-btn" @click="logout">退出登录</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 状态管理
const userInfo = ref({});
const isLoading = ref(true);
const loadError = ref(false);
const errorMsg = ref('');
const debugInfo = ref('');

// 页面加载时获取用户信息
onLoad(async () => {
  await fetchUserInfo();
});

// 核心：获取用户信息
const fetchUserInfo = async () => {
  try {
    loadError.value = false;
    errorMsg.value = '';
    debugInfo.value = '';
    isLoading.value = true;

    // 1. 读取缓存的登录信息
    const isLogin = uni.getStorageSync('isLogin');
    const storedUser = uni.getStorageSync('userInfo');
    const debugLogs = [
      `缓存的登录状态: ${isLogin}`,
      `缓存的用户信息: ${JSON.stringify(storedUser)}`
    ];

    // 2. 校验登录状态和userId
    if (!isLogin) {
      throw new Error('未登录，请先登录');
    }
    if (!storedUser?.userId) {
      throw new Error('用户信息中缺少userId');
    }

    // 3. 转换userId为数字类型（与后端Long匹配）
    const userId = Number(storedUser.userId);
    if (isNaN(userId)) {
      throw new Error(`userId格式错误（${storedUser.userId}），无法转换为数字`);
    }
    debugLogs.push(`转换后的userId（数字类型）: ${userId}`);

    // 4. 调用接口（传递数字类型参数）
    const res = await uni.request({
      url: 'http://localhost:6006/user-client/api/loginInfo/getUserInfo',
      method: 'POST',
      data: { 
        userId: userId 
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      timeout: 10000
    });

    // 5. 记录接口响应详情
    debugLogs.push(`接口状态码: ${res.statusCode}`);
    debugLogs.push(`接口响应体: ${JSON.stringify(res.data)}`);
    debugInfo.value = debugLogs.join('\n');

    // 6. 处理响应
    if (res.statusCode !== 200) {
      throw new Error(`请求失败（状态码: ${res.statusCode}）`);
    }
    if (!res.data) {
      throw new Error('接口返回空数据');
    }
    if (res.data.code !== 0) {
      throw new Error(`业务错误: ${res.data.msg || '未知错误'}`);
    }

    // 7. 成功更新页面数据（包含userType和userAddress）
    userInfo.value = res.data.data;
    console.log('用户信息加载成功:', userInfo.value);

  } catch (error) {
    loadError.value = true;
    errorMsg.value = error.message;
    console.error('加载失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 重试加载
const reload = () => {
  fetchUserInfo();
};

// 页面跳转
const goToRecharge = () => {
  uni.navigateTo({ url: '/pages/recharge/recharge' });
};

const goToBills = () => {
  uni.navigateTo({ url: '/pages/bills/bills' });
};
const goToPhones = () => {
  uni.navigateTo({ url: '/pages/phone/phone' });
};

// 退出登录
const logout = () => {
  uni.showModal({
    title: '确认退出',
    content: '您确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('isLogin');
        uni.removeStorageSync('userInfo');
        uni.redirectTo({ url: '/pages/login/login' });
      }
    }
  });
};
</script>

<style scoped>
.profile-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
}

.loading-icon {
  width: 60rpx;
  height: 60rpx;
}

.spinner {
  width: 100%;
  height: 100%;
  border: 6rpx solid rgba(0, 122, 255, 0.1);
  border-radius: 50%;
  border-top-color: #007AFF;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading text {
  margin-top: 20rpx;
  font-size: 30rpx;
  color: #666;
}

.load-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
}

.load-error text {
  margin-bottom: 20rpx;
  font-size: 30rpx;
  color: #ff4d4f;
}

.debug-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #666;
  max-width: 90%;
  white-space: pre-wrap;
  text-align: left;
}

/* 用户信息区域样式（新增类型和地址的样式） */
.user-info {
  background-color: #007AFF;
  padding: 40rpx 30rpx;
  display: flex;
  align-items: flex-start; /* 顶部对齐，避免内容换行后错位 */
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  margin-top: 5rpx; /* 微调与文字的垂直对齐 */
}

.avatar image {
  width: 100%;
  height: 100%;
}

.user-detail {
  margin-left: 30rpx;
  color: #fff;
  padding: 5rpx 0;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 12rpx;
}

.user-id, .user-type, .user-address {
  font-size: 26rpx;
  opacity: 0.9;
  display: block;
  margin-bottom: 8rpx; /* 每条信息之间的间距 */
}

/* 菜单和按钮样式不变 */
.profile-menu {
  margin: 20rpx;
}

.menu-group {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  height: 100rpx;
  border-bottom: 1px solid #f5f5f5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.menu-icon image {
  width: 36rpx;
  height: 36rpx;
}

.menu-text {
  flex: 1;
  font-size: 32rpx;
  color: #333;
}

.menu-amount {
  font-size: 30rpx;
  color: #666;
  margin-right: 20rpx;
}

.menu-arrow {
  width: 24rpx;
  height: 24rpx;
  opacity: 0.5;
}

.logout-btn {
  width: calc(100% - 40rpx);
  height: 100rpx;
  line-height: 100rpx;
  background-color: #fff;
  color: #FF4D4F;
  font-size: 34rpx;
  border-radius: 8rpx;
  margin: 0 20rpx;
  border: 1px solid #FF4D4F;
}
</style>